package org.jeecg.modules.system.controller;



import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.encryption.AesEncryptUtil;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-20
 */
@Api(tags="用户管理")
@Slf4j
@RestController
@RequestMapping("/api/app/sys/user")
public class ApiSysUserController {
	@Autowired
	private ISysUserService sysUserService;

	/**
	 * 首页用户重置密码
	 */
	@RequestMapping(value = "/updatePassword", method = RequestMethod.PUT)
    @ApiOperation(value="首页用户重置密码", notes="首页用户重置密码")
	public Result<?> changPassword(@RequestBody JSONObject json) {
		String username =  json.getString("username");
		String oldpassword = "";
		String password = "";
		String confirmpassword = "";

		// update-begin-by wujinbiao 2022/3/24 9:31 for 解密参数
        try {
            oldpassword = AesEncryptUtil.desEncrypt(json.getString("oldpassword"));
            // 处理解密后字符串会多出 \u0000 问题 create by wjb 2022-03-24
            oldpassword = oldpassword.replaceAll("[\u0000]","");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("旧密码解密失败!");
        }
        try {
            password = AesEncryptUtil.desEncrypt(json.getString("password"));
            password = password.replaceAll("[\u0000]","");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("新密码解密失败!");
        }
        try {
            confirmpassword = AesEncryptUtil.desEncrypt(json.getString("confirmpassword"));
            confirmpassword = confirmpassword.replaceAll("[\u0000]","");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("确认密码解密失败!");
        }
		// update-end-by wujinbiao 2022/3/24 9:31 for 解密参数


		SysUser user = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
		if(user==null) {
			return Result.error("用户不存在！");
		}
		return sysUserService.resetPassword(username,oldpassword,password,confirmpassword);
	}
}
